package com.dt.tree.utils;

import com.dt.tree.domain.TreeNode;

import java.util.ArrayList;
import java.util.List;

/**
 * 组织机构树工具类
 */
public class TreeUtils {

	public static void main( String[] args ) {
		List< TreeNode > list = new ArrayList<>( );
		for ( int i = 2 ; i < 4 ; i++ ) {
			TreeNode treeNode = new TreeNode( );
			treeNode.setId( i + "" );
			treeNode.setParentId( "1" );
			list.add( treeNode );
		}
		for ( int i = 6 ; i < 10 ; i++ ) {
			TreeNode treeNode = new TreeNode( );
			treeNode.setId( i + "" );
			treeNode.setParentId( "2" );
			list.add( treeNode );
		}
		for ( int i = 15 ; i < 20 ; i++ ) {
			TreeNode treeNode = new TreeNode( );
			treeNode.setId( i + "" );
			treeNode.setParentId( "6" );
			list.add( treeNode );
		}
		TreeNode rootNode = new TreeNode( );
		rootNode.setId( "1" );
		rootNode.setParentId( "0" );
		List< TreeNode > rootChild = buildTree( list , rootNode );
		rootNode.setChildren( rootChild );
		System.out.println( rootNode );
	}

	/**
	 * 建树  建立除去根节点的 树
	 *
	 * @param treeNodes
	 * @param rootNode
	 * @return
	 */
	public static List< TreeNode > buildTree( List< TreeNode > treeNodes , TreeNode rootNode ) {
		List< TreeNode > tree = new ArrayList<>( );
		for ( TreeNode treeNode : treeNodes ) {
			if ( rootNode.getId( ).equals( treeNode.getParentId( ) ) ) {
				TreeNode children = findChildren( treeNodes , treeNode , 3 );
				children.setLabel( "2" );
				tree.add( children );
			}
		}
		return tree;
	}

	/**
	 * 获取孩子节点
	 *
	 * @param treeNodes
	 * @param parentNode
	 * @return
	 */
	public static TreeNode findChildren( List< TreeNode > treeNodes , TreeNode parentNode , int level ) {
		for ( TreeNode treeNode : treeNodes ) {
			if ( parentNode.getId( ).equals( treeNode.getParentId( ) ) ) {
				if ( parentNode.getChildren( ) == null ) {
					parentNode.setChildren( new ArrayList<>( ) );
				}
				treeNode.setLabel( level + "" );
				parentNode.add( findChildren( treeNodes , treeNode , level + 1 ) );
			}
		}
		return parentNode;
	}
}